package com.wanwanbear.www.redpacket.service;

import android.accessibilityservice.AccessibilityService;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityWindowInfo;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;


public class CatchMoneyService extends AccessibilityService {

    private List<AccessibilityNodeInfo> parents;
    private PowerManager powerManager;
    PowerManager.WakeLock wakeLock;
    KeyguardManager keyguardManager;
    KeyguardManager.KeyguardLock keyguardLock;

    /**
     * 当启动服务的时候就会被调用
     */
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        parents = new ArrayList<>();
    }

    /**
     * 监听窗口变化的回调
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        int eventType = event.getEventType();
        switch (eventType) {
            //当通知栏发生改变时
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
                Log.e("tag","状态栏变化");
                List<CharSequence> texts = event.getText();
                if (!texts.isEmpty()) {
                    for (CharSequence text : texts) {
                        String content = text.toString();
                        if (content.contains("[微信红包]")) {
                            //模拟打开通知栏消息，即打开微信
                            if (event.getParcelableData() != null &&
                                    event.getParcelableData() instanceof Notification) {
                                wakeAndUnlock(true);
                                Notification notification = (Notification) event.getParcelableData();
                                PendingIntent pendingIntent = notification.contentIntent;
                                try {
                                    pendingIntent.send();
                                    Log.e("demo","进入微信");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
                break;
            //当窗口的状态发生改变时
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                String className = event.getClassName().toString();
                Log.e("className",className);
                if (className.equals("com.tencent.mm.ui.LauncherUI")) {
                    //点击最后一个红包
                    Log.e("demo","点击红包");
                    getLastPacket();
                } else if (className.equals("com.tencent.mm.plugin.luckymoney.ui.En_fba4b94f")) {
                    //开红包
                    Log.e("demo","开红包");
                    inputClick("com.tencent.mm:id/bp6");
                } else if (className.equals("com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI")) {

                    //退出红包
                    Log.e("demo","退出红包");
                    inputClick("com.tencent.mm:id/bmu");
                    wakeAndUnlock(false);
                }
                break;
        }
    }

    /**
     * 通过ID获取控件，并进行模拟点击
     * @param clickId
     */
    private void inputClick(final String clickId) {
        new Handler().postDelayed(new Runnable(){
            @TargetApi(Build.VERSION_CODES.N)
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public void run() {
                AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
/*                List<AccessibilityWindowInfo> accessibilityWindowInfos = getWindows();
                if (accessibilityWindowInfos.isEmpty()) {
                    Log.e("tag", "accessibilityWindowInfos为空");
                }
                Log.e("accessibilityWindowInfo", String.valueOf(accessibilityWindowInfos.indexOf(1)));
                for (AccessibilityWindowInfo accesibilityWindowsInfo : accessibilityWindowInfos
                        ) {
                    Log.e("tag", "accesibilityWindowsInfo------->" + accesibilityWindowsInfo.getAnchor());
                    AccessibilityNodeInfo a = accesibilityWindowsInfo.getAnchor();
                    List<AccessibilityNodeInfo> l = a.findAccessibilityNodeInfosByViewId(clickId);
                    if(l!=null){
                        Log.e("accesibilityWindowsInfo","accesibilityWindowsInfo.list不为空");
                    }
                }*/
                if (nodeInfo == null) {
                    Log.e("tag", "nodeInfo为空-------->");
                } else {
                    //Log.e("tag",nodeInfo.getViewIdResourceName());
                    if (nodeInfo.findAccessibilityNodeInfosByViewId(clickId) != null) {
                        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId(clickId);
                        for (AccessibilityNodeInfo item : list) {
                            Log.e("tag", item.toString());
                            item.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                        }
                    }
                }
            }
        }, 1000);


        }

    /**
     * 获取List中最后一个红包，并进行模拟点击
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void getLastPacket() {
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        recycle(rootNode);
        if(parents.size()>0){
            parents.get(parents.size() - 1).performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
    }

    /**
     * 回归函数遍历每一个节点，并将含有"领取红包"存进List中
     *
     * @param info
     */
    public void recycle(AccessibilityNodeInfo info) {
        if(info == null){
            return;
        }
        if (info.getChildCount() == 0) {
            if (info.getText() != null) {
                if ("领取红包".equals(info.getText().toString())) {
                    if (info.isClickable()) {
                        info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    }
                    AccessibilityNodeInfo parent = info.getParent();
                    while (parent != null) {
                        if (parent.isClickable()) {
                            parents.add(parent);
                            break;
                        }
                        parent = parent.getParent();
                    }
                }
            }
        } else {
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    recycle(info.getChild(i));
                }
            }
        }
    }

    /**
     * 中断服务的回调
     */
    @Override
    public void onInterrupt() {

    }

    @RequiresApi(api = Build.VERSION_CODES.DONUT)
    private void wakeAndUnlock(boolean b)
    {
        if(b)
        {
            //获取电源管理器对象
            powerManager =(PowerManager) getSystemService(Context.POWER_SERVICE);

            //获取PowerManager.WakeLock对象，后面的参数|表示同时传入两个值，最后的是调试用的Tag
            wakeLock = powerManager.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");

            if(!powerManager.isScreenOn()) {
                Log.e("tag","点亮屏幕");
                //点亮屏幕
                wakeLock.acquire();
            }
            //得到键盘锁管理器对象
            keyguardManager= (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
            keyguardLock = keyguardManager.newKeyguardLock("unLock");
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
            //解锁
            keyguardLock.disableKeyguard();
            Log.e("tag","锁状态------------->"+keyguardManager.inKeyguardRestrictedInputMode());
            Toast.makeText(this,"解锁",Toast.LENGTH_SHORT).show();
            Log.e("tag","解锁");
        }
        else
        {
            //锁屏
            keyguardLock.reenableKeyguard();

            //释放wakeLock，关灯
            wakeLock.release();
        }

    }
}
